import { JsCodeEncoder } from "./JsCodeEncoder";
import * as ejs from 'ejs'
import { OpenApi } from "./OpenApi";
import { ApplyMethodsParamItem } from "./VueCodeGenerator";

export enum EjsType {
  LOCAL_FILE,
  NETWORK_URL,
  TEXT_CONTENT
}

export class EjsCodeEncoder extends JsCodeEncoder {
  template: string
  type: EjsType = EjsType.TEXT_CONTENT
  ejsContent: string
  renderContent: string
  data?: any
  options?: any

  constructor(template: string, type: EjsType = EjsType.TEXT_CONTENT) {
    super([]);
    this.template = template
    this.type = type
  }

  async getEjsContent() {
    if(this.type === EjsType.TEXT_CONTENT) {
      this.ejsContent = this.template
    }
    if(this.type === EjsType.NETWORK_URL) {
      this.ejsContent = await fetch(this.template).then((res) => res.text())
    }
    if(this.type === EjsType.LOCAL_FILE) {
      var _BOM = /^\uFEFF/;
      this.ejsContent = ejs.fileLoader(this.template, {
        encoding: 'UTF-8'
      }).toString().replace(_BOM, '');
    }
    this.renderContent = this.ejsContent
  }

  async encode(): Promise<string> {
    await this.getEjsContent()
    if(this.data) {
      this.renderContent = ejs.render(this.ejsContent, this.data, this.options)
    }
    return this.renderContent
  }

  async applyMethods(openapi: OpenApi, params: ApplyMethodsParamItem[], ejsData?: any, ejsOptions?: any) {
    // 转换数据
    var data = {
      openapi: openapi.toJsonObject(),
      params: params.map((item) => ({
        ...item,
        apiMethod: item.apiMethod.toJsonObject()
      })),
      ...ejsData
    }
    this.data = data
    this.options = ejsOptions

    console.log(data)
    console.log(ejsOptions)
  }
}